<template>
   <div style="height: 600px;">
      <!-- 动态查询 -->
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
         <el-form-item label="讲师名称" prop="nickname">
            <el-input v-model="queryParams.nickname" placeholder="请输入角色名称" clearable style="width: 240px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="所带班级" prop="classId">
            <el-tree-select accordion="true" v-model="queryParams.classId" clearable
               :props="{ label: 'name', children: 'children', value: 'classId' }" :data="cacheData"
               style="width: 220px" />
         </el-form-item>
         <el-form-item label="账号状态" prop="state">
            <el-select v-model="queryParams.state" placeholder="账号状态" clearable style="width: 240px">
               <el-option v-for="dict in optionsStatus" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item label="讲师性别" prop="sex">
            <el-select v-model="queryParams.sex" placeholder="讲师性别" clearable style="width: 240px">
               <el-option v-for="dict in optionsSex" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item label="创建时间" style="width: 308px;font-weight: 700;">
            <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD" type="daterange"
               range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:role:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
               v-hasPermi="['system:role:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['system:role:remove']">删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
               v-hasPermi="['system:role:export']">导出</el-button>
         </el-col>
         <el-row style="margin-left: 62.5%;">
            <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top"
               v-if="search">
               <el-button circle icon="Search" @click="toggleSearch()" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
               <el-button circle icon="Refresh" @click="refresh()" />
            </el-tooltip>
         </el-row>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange"
         :header-cell-style="{ background: '#eee', color: '#909399' }">
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="教师编号" type="index" width="80" />
         <el-table-column label="账号" prop="username" :show-overflow-tooltip="true" width="80" />
         <el-table-column label="用户名" prop="nickname" :show-overflow-tooltip="true" width="80" />
         <el-table-column label="性别" prop="sex" :show-overflow-tooltip="true" width="80">
            <template #default="scope">
               {{ scope.row.sex == 1 ? '女' : '男' }}
            </template>
         </el-table-column>
         <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" width="130" />
         <el-table-column label="手机号" prop="phone" :show-overflow-tooltip="true" width="100" />
         <el-table-column label="头像" prop="avatar" width="100">
            <template #default="scope">
               <el-avatar :size="50" style="width: 30px; height: 30px" :src="scope.row.avatar" />
            </template>
         </el-table-column>
         <el-table-column label="所带班级" prop="classList.className" width="80">
            <template #default="scope">
               <p v-for="item in scope.row.classList">{{ item.className }}</p>
            </template>
         </el-table-column>

         <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
               <el-switch v-model="scope.row.state" :active-value="0" :inactive-value="1"
                  @click="handleStatusChange(scope.row)">
               </el-switch>
            </template>
         </el-table-column>
         <el-table-column label="创建时间" align="center" prop="createTime">
            <template #default="scope">
               <span>{{ scope.row.createTime }}</span>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip>
               <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:role:remove']"></el-button>
               </el-tooltip>
               <el-tooltip content="重置密码" placement="top">
                  <el-button link type="primary" icon="Key" @click="handleAuthUser(scope.row)"
                     v-hasPermi="['system:role:edit']"></el-button>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>
   </div>
   <el-pagination background v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 15, 20, 25]" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
   <!-- 添加或修改角色配置对话框 -->
   <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
         <el-form-item label="讲师账号" prop="username">
            <el-input v-model="form.username" placeholder="请输入讲师账号" />
         </el-form-item>

         <el-form-item label="讲师密码" prop="password" v-show="menuExpand">
            <el-input v-model="form.password" placeholder="请输入讲师密码" />
         </el-form-item>

         <el-form-item label="讲师名称" prop="nickname">
            <el-input v-model="form.nickname" placeholder="请输入讲师名称" />
         </el-form-item>

         <el-form-item label="讲师性别" prop="sex">
            <el-radio-group v-model="form.sex" class="ml-4">
               <el-radio :value="0" size="large">男</el-radio>
               <el-radio :value="1" size="large">女</el-radio>
            </el-radio-group>
         </el-form-item>

         <el-form-item label="讲师邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入讲师邮箱" />
         </el-form-item>

         <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
         </el-form-item>

         <el-form-item label="讲师头像" prop="avatar">
            <el-upload class="avatar-uploader" action="/api/admin/teacher/upload" :show-file-list="false"
               :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
               <img v-if="imageUrl" :src="imageUrl" class="avatar" style="max-width: 150px;" />
               <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
               </el-icon>
            </el-upload>
         </el-form-item>
      </el-form>
      <template #footer>
         <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
         </div>
      </template>
   </el-dialog>
</template>

<script setup>
import { adminTeacherList, adminClassList, adminTeacherAdd, adminTeacherById, adminTeacherUpdate, adminTeacherStatus, adminTeacherDelete, adminTeacherPassword, exportOrder } from "@/api/admin/teacher/index.js";
import { ref, onMounted, getCurrentInstance, reactive } from 'vue';
import { stu_list_tree } from "@/api/admin/student/student_api.js"
import { ElMessage, ElMessageBox } from 'element-plus';
const { proxy } = getCurrentInstance();

const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(5);
const title = ref("");
const options = ref([])
const cacheData = ref([])  //懒加载
const menuExpand = ref(true);
//讲师表单
let form = ref({
   id: '',
   username: '',
   password: '',
   nickname: '',
   avatar: '',
   classId: '',
   sex: '',
   phone: ''
})
const optionsStatus = [{
   value: '0',
   label: '正常',
},
{
   value: '1',
   label: '停用',
}]
const optionsSex = [{
   value: '1',
   label: '女',
},
{
   value: '0',
   label: '男',
}]
//动态查询
const queryParams = ref({
   pageNum: 1,
   pageSize: 10,
   nickname: '',
   state: '',
   classId: '',
   createTime: [],
   sex: ''
})
//分页
const handleSizeChange = (val) => {
   queryParams.value.pageSize = val
   getList()
}
const handleCurrentChange = (val) => {
   queryParams.value.pageNum = val
   getList()
}
//图片
const imageUrl = ref('')
//图片回显
const handleAvatarSuccess = ( 
   response,
   uploadFile
) => {
   imageUrl.value = URL.createObjectURL(uploadFile.raw)
   form.value.avatar = uploadFile.response.obj
}
const beforeAvatarUpload = (rawFile) => {
   const isImage = rawFile.type === 'image/png' || rawFile.type === 'image/jpeg';
if (!isImage) {
  ElMessage.error('图片格式必须为png或jpg!');
  return false;
}
if (rawFile.size / 1024 / 1024 > 5) {
  ElMessage.error('图片大小不能超过5MB!');
  return false;
}
return true;
}
//班级动态菜单
stu_list_tree().then(res => {
   cacheData.value = res.data.obj[0].children
})
onMounted(() => {
   getList();
   getShow();
})
const rules = reactive({
   username: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
   password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
   nickname: [{ required: true, message: '讲师名称不能为空', trigger: 'blur' }, { pattern: /^[\u4e00-\u9fa5]+$/, message: '名称必须是中文', trigger: 'blur' }],
   classId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
   sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
   email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }, { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '邮箱格式错误', trigger: 'blur' }],
   phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对', trigger: 'blur' }],
})
/** 查询讲师列表 */
function getList() {
   loading.value = true;
   adminTeacherList(queryParams.value).then(response => {
      roleList.value = response.data.obj.records;
      total.value = response.data.obj.total;
      loading.value = false;
   });
}
// 查询班级列表
function getShow() {
   adminClassList().then(res => {
      if (res.data.code == 200) {
         options.value = res.data.obj
      }
   })
}

/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   queryParams.value.classId = '';
   queryParams.value.nickname = '';
   queryParams.value.state = '';
   queryParams.value.sex = '';
   queryParams.value.createTime = [];
   handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
   if (ids.value.length > 0) {
      ids.value.forEach(arr => {
         adminTeacherDelete(arr).then(res => {
            getList()
         })
      });
      ElMessage.success('删除成功')
   } else {
      if (row.classList.length > 0) {
         ElMessage.error('该教师带有班级,无法删除')
         getList()
      } else {
         ElMessageBox.confirm(
            '您确认要删除讲师编号为' + row.userId + '的数据项?',
            '温馨提示',
            {
               confirmButtonText: '确认',
               cancelButtonText: '取消',
               type: 'warning',
            }).then(() => {
               adminTeacherDelete(row.userId).then(res => {
                  if (res.data.code == 200) {
                     ElMessage.success('删除成功')
                     getList()
                     ids.value = []
                  } else {
                     ElMessage.error(res.data.message)
                     getList()
                  }
               })
            })
            .catch(() => {
               ElMessage({
                  type: 'info',
                  message: '已取消删除',
               })
            })
      }
   }
}
/** 导出按钮操作 */
function handleExport() {
   exportOrder().then(res => {
      const xlsx = "application/vnd.ms-excel";
      const blob = new Blob([res.data], { type: xlsx });
      const a = document.createElement("a");
      let fileName = "讲师信息" + new Date().getTime() + ".xlsx";
      a.download = fileName;
      a.href = window.URL.createObjectURL(blob)
      a.click()
      a.remove()
   });
}
const classLists = ref(null)
/** 多选框选中数据 */
function handleSelectionChange(selection) {
   classLists.value = []
   ids.value = []
   selection.forEach(arr => {
      ids.value.push(arr.userId)
      classLists.value = arr.classList
   });
   single.value = selection.length != 1;
   multiple.value = !selection.length;
   if (classLists.value.length != 0) {
      multiple.value = classLists.value.length != 0
   }
}
/** 讲师状态修改 */
function handleStatusChange(row) {
   let text = row.state === 0 ? "启用" : "停用";
   ElMessageBox.confirm(
      '您确认要'+text+'该的讲师账号嘛?',
      '温馨提示',
      {
         confirmButtonText: '确认',
         cancelButtonText: '取消',
         type: 'warning',
      }).then(() => {
         adminTeacherStatus(row.userId).then(res => {
            if (res.data.code == 200) {
               ElMessage.success(text + '成功')
            }
         })
      })
      .catch(() => {
         ElMessage({
            type: 'info',
            message: '已取消删除',
         })
         getList()
      })
}


/** 重置新增的表单以及其他数据  */
function reset() {
   form.value = {
      id: undefined,
      username: undefined,
      password: undefined,
      nickname: undefined,
      avatar: undefined,
      sex: undefined,
      email: undefined,
   };
}
/** 添加讲师 */
function handleAdd() {
   reset();
   open.value = true;
   title.value = "添加讲师";
}
/** 修改讲师 */
function handleUpdate(row) {
   const uid = ref(row.userId);
   const id = ref(0);
   ids.value.forEach(arr => {
      id.value = arr
   });
   if (id.value != 0) {
      uid.value = id.value
   }
   menuExpand.value = false
   reset();
   adminTeacherById(uid.value).then(response => {
      form.value = response.data.obj;
      form.value.id = response.data.obj.userId
      open.value = true;
      title.value = "修改讲师";
   });
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
         if (form.value.id != undefined) {
            adminTeacherUpdate(form.value).then(response => {
               ElMessage.success("修改成功");
               open.value = false;
               getList();
            });
         } else {
            adminTeacherAdd(form.value).then(response => {
               if (response.data.code == 200) {
                  ElMessage.success("新增成功");
                  open.value = false;
                  getList();
               } else {
                  ElMessage.error(response.data.message)
                  open.value = false;
                  getList();
               }
            });
         }
      }
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

// 重置密码
function handleAuthUser(row) {
   adminTeacherPassword(row.userId).then(res => {
      if (res.data.code == 200) {
         ElMessage.success('已重置密码')
      }
   })
}
const props = defineProps({
   /* 是否显示检索条件 */
   showSearch: {
      type: Boolean,
      default: true,
   },
   /* 显隐列信息 */
   columns: {
      type: Array,
   },
   /* 是否显示检索图标 */
   search: {
      type: Boolean,
      default: true,
   },
   /* 显隐列类型（transfer穿梭框、checkbox复选框） */
   showColumnsType: {
      type: String,
      default: "checkbox",
   },
   /* 右外边距 */
   gutter: {
      type: Number,
      default: 10,
   },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

// 搜索
function toggleSearch() {
   if (showSearch.value == true) {
      showSearch.value = false
   } else {
      showSearch.value = true
   }
   emits("update:showSearch", !props.showSearch);
}

// 刷新
function refresh() {
   getList()
}
</script>
<style>
.avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
   border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 178px;
   height: 178px;
   text-align: center;
}

/* main-container全局样式 */
.app-container {
   padding: 20px;
}

label {
   font-weight: 700;
}
</style>
